package auth

import (
	"strings"

	"gitee.com/micro-plat/sas/sas/modules/const/enum"
	"gitee.com/micro-plat/sas/sas/modules/util"

	"github.com/micro-plat/lib4go/security/rsa"
	"github.com/micro-plat/lib4go/types"
)

func getSecretName(eType string, isSign bool) string {
	if strings.EqualFold(eType, "rsa") {
		if isSign {
			return "rsa_public_secret"
		}
		return "rsa_private_secret"
	}

	return enum.GetNameByType(eType)
}

//getSignKey 获取签名密钥
func getSignKey(info types.XMap, signType, encodeKey string, authType int) (signKey string, signRsaType string, err error) {

	//动态验证时，密钥为请求传入的加密后的aes密钥，由本地rsa私钥解密
	if authType == enum.Dynamic {
		rsaPriKey, err1 := util.AESDecrypt(info.GetString("rsa_private_secret"), util.MD5(info.GetString("uid")))
		if err1 != nil {
			return "", "", err1
		}

		signKey, err = util.RSADecrypt(encodeKey, rsaPriKey, strings.ToUpper(info.GetString("rsa_type", rsa.PKCS8)))
		return
	}

	//其它类型验证的秘钥及本地数据库密钥
	signKey, err = util.AESDecrypt(info.GetString(getSecretName(signType, true)), util.MD5(info.GetString("uid")))
	if err != nil {
		return
	}
	//如果是rsa签名,需要返回rsa签名密钥的类型
	if strings.EqualFold(signType, "rsa") {
		signRsaType = info.GetString("rsa_type", rsa.PKCS8)
	}
	return
}

//getDecryptKey 获取解密密钥
func getDecryptKey(info types.XMap, decryptType string, authType int, signKey string) (decryptKey, decryptRsaType string, err error) {
	switch authType {
	case enum.Single:
		//单方验证时无解密密钥
		return
	case enum.Dynamic:
		//动态验证时，解密密钥与签名密钥一致
		decryptKey = signKey
		return
	default:
		//其它类型的解密密钥为本地密钥
		decryptKey, err = util.AESDecrypt(info.GetString(getSecretName(decryptType, false)), util.MD5(info.GetString("uid")))
		if err != nil {
			return
		}
		//如果是rsa解密,需要返回rsa密钥的类型
		if strings.EqualFold(decryptType, "rsa") {
			decryptRsaType = info.GetString("rsa_type", rsa.PKCS8)
		}
		return
	}
}
